using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
using EnvDTE;
using Microsoft.Practices.Common;
using Microsoft.Practices.RecipeFramework.Extensions.References.VisualStudio;

namespace Microsoft.Practices.RepositoryFactory.References
{
    /// <summary/>
    [Serializable]
    public class ProjectWithFilesReference : ProjectPropertyReferenceAny, IAttributesConfigurable
    {
        private const string ExtensionAttribute = "Extension";
        private string fileExtension;
        
        /// <summary>
        /// Initializes a new instance of the <see cref="T:ProjectWithFilesReference"/> class.
        /// </summary>
        /// <param name="recipe">The recipe.</param>
        public ProjectWithFilesReference(string recipe)
            : base(recipe)
        {
        }

        #region Public Implementation

        /// <summary>
        /// Performs the validation of the item passed as target
        /// Returns true if the reference is allowed to be executed in the target
        /// that is if the target is a project that has the mapping property.
        /// </summary>
        /// <param name="target"></param>
        /// <returns></returns>
        public override bool IsEnabledFor(object target)
        {
            Project project = target as Project;
            bool extensionFounded = false;

            if(project != null)
            {
                VerifyExtensions(project.ProjectItems, ref extensionFounded);
            }

            return extensionFounded && base.IsEnabledFor(target);
        } 

        #endregion

        #region Private Implementation

        private void VerifyExtensions(ProjectItems items, ref bool extensionFounded)
        {
            if(!extensionFounded)
            {
                if (items == null)
                {
                    return;
                }

                foreach(ProjectItem item in items)
                {
                    bool isFolder = true;
                    // if we don't find the ExtensionAttribute property or the value is null, then this is a folder
                    foreach (Property property in item.Properties)
                    {
                        if (string.Compare(property.Name, ExtensionAttribute, 
                            StringComparison.InvariantCultureIgnoreCase) == 0)
                        {
                            isFolder = (property.Value == null);
                            break;
                        }
                    }

                    if(isFolder)
                    {
                        VerifyExtensions(item.ProjectItems, ref extensionFounded);
                    }
                    else
                    {
                        if (item.Name.EndsWith(fileExtension, 
                            StringComparison.InvariantCultureIgnoreCase))
                        {
                            extensionFounded = true;
                            return;
                        }
                    }
                }
            }
        } 

        #endregion

        #region ISerializable Members

        /// <summary>
        /// Provides a serialization member that derived classes can override to add
        /// data to be stored for serialization.
        /// </summary>
        /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the reference.</param>
        /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
        [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
        protected override void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue(ExtensionAttribute, fileExtension);
            base.GetObjectData(info, context);
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="T:ProjectWithFilesReference"/> class.
        /// </summary>
        /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo"/> that holds the serialized object data about the reference.</param>
        /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains contextual information about the source or destination.</param>
        protected ProjectWithFilesReference(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            fileExtension = info.GetString(ExtensionAttribute);
        }

        #endregion

        #region IAttributesConfigurable Members

        /// <summary>
        /// Configures the component using the dictionary of attributes specified
        /// in the configuration file.
        /// </summary>
        /// <param name="attributes">The attributes in the configuration element.</param>
        public override void Configure(StringDictionary attributes)
        {
            if (attributes == null)
                throw new ArgumentNullException("attributes");

            if (attributes.ContainsKey(ExtensionAttribute))
            {
                fileExtension = attributes[ExtensionAttribute];
            }

            base.Configure(attributes);
        }

        #endregion
    }
}
